package com.rong.mbt.personal.activity;


import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.PixelFormat;
import android.hardware.Camera;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.rong.mbt.personal.R;
import com.rong.mbt.personal.bean.BaseBean;
import com.rong.mbt.personal.bean.FaceGetImgBean;
import com.rong.mbt.personal.face.CameraPreview;
import com.rong.mbt.personal.face.DetectorProxy;
import com.rong.mbt.personal.face.FaceRectView;
import com.rong.mbt.personal.face.ICameraCheckListener;
import com.rong.mbt.personal.utils.AESDEecode;
import com.rong.mbt.personal.utils.DlgUtil;
import com.vise.log.ViseLog;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import sun.misc.BASE64Encoder;


public class FaceRecognitionActivity extends PBaseActivity {

    private CameraPreview mFace_detector_preview;
    private FaceRectView mFace_detector_face;
    private Button mFace_detector_take_photo;

    private Context mContext;
    private DetectorProxy mDetectorProxy;


    private ICameraCheckListener mCameraCheckListener = new ICameraCheckListener() {
        @Override
        public void checkPermission(boolean isAllow) {
            if (!isAllow) {
                Toast.makeText(mContext, "权限申请被拒绝，请进入设置打开权限再试！", Toast.LENGTH_SHORT).show();
                finish();
            }
        }

        @Override
        public void checkPixels(long pixels, boolean isSupport) {
            ViseLog.i("checkPixels" + pixels);
            if (!isSupport) {
                Toast.makeText(mContext, "手机相机像素达不到要求！", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    };
    private String mbtToken;
    private ImageView iv;

    private boolean isUploadFace = false; //是否上传过人脸识别图片  false 否  true是
    private String Base64NetStr = null;
    private Bitmap netBitmap;  //获取到的人脸图片
    private ProgressDialog progressDialog;

    @Override
    public int getLayoutId() {
        return R.layout.activity_face_recognition;
    }

    @Override
    public void initView() {
        super.initView();
        mContext = this;
        mbtToken = getIntent().getStringExtra("mbtToken");
        init();
        getFaceImg();
    }

    protected void init() {
        mFace_detector_preview = (CameraPreview) findViewById(R.id.face_detector_preview);
        mFace_detector_face = (FaceRectView) findViewById(R.id.face_detector_face);
        mFace_detector_face.setZOrderOnTop(true);
        mFace_detector_face.getHolder().setFormat(PixelFormat.TRANSLUCENT);
        mFace_detector_take_photo = (Button) findViewById(R.id.face_detector_take_photo);

        iv = findViewById(R.id.iv);
        mFace_detector_take_photo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                progressDialog = DlgUtil.showProgressDlg(mContext, "请稍等...");
                progressDialog.show();
                mFace_detector_take_photo.setEnabled(false);
                mFace_detector_preview.getCamera().takePicture(new Camera.ShutterCallback() {
                    @Override
                    public void onShutter() {

                    }
                }, null, new Camera.PictureCallback() {
                    @Override
                    public void onPictureTaken(byte[] bytes, Camera camera) {
                        mFace_detector_preview.getCamera().stopPreview();
                        if (!isUploadFace) {
                            //没有上传过人脸识别
                            byte2file(bytes, "face.jpg");
                        } else {
                            //上传过人脸识别  两个图片的base64 编码做比较

                            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
                            String Base64LocalStr = encodeImage(bitmap);
                            Log.i("test", "111111  " + Base64LocalStr);
                            OkGo.<String>post("http://service.kantingyong.com/face/verify")
                                    .tag(this)
//                                    .isMultipart(true)
                                    .headers("mbtToken", mbtToken)
                                    .params("type", 1)
                                    .params("content_1", Base64LocalStr)
                                    .params("content_2", Base64LocalStr)
                                    .execute(new StringCallback() {
                                        @Override
                                        public void onSuccess(Response<String> response) {
                                            //{"msg":"上传成功","resultCode":0}
                                            Log.i("test", "onsuccess111  " + response.body());
                                            mFace_detector_take_photo.setEnabled(true);
                                            if (progressDialog != null) {
                                                progressDialog.cancel();
                                            }
                                        }

                                        @Override
                                        public void onError(Response<String> response) {
                                            super.onError(response);
                                            Log.i("test", "onError222  " + response.body()+"  "+response.message());
                                            mFace_detector_take_photo.setEnabled(true);
                                            if (progressDialog != null) {
                                                progressDialog.cancel();
                                            }
                                            resetinit();
                                        }
                                    });
                        }
                    }
                });
            }
        });
        mDetectorProxy = new DetectorProxy.Builder(mFace_detector_preview)
                .setMinCameraPixels(3000000)
                .setCheckListener(mCameraCheckListener)
                .setFaceRectView(mFace_detector_face)
                .setDrawFaceRect(true)
                .build();
    }

    public void resetinit() {
        if (mDetectorProxy != null) {
            mDetectorProxy.release();
            mDetectorProxy.detector();
            mDetectorProxy.openCamera();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mDetectorProxy != null) {
            mDetectorProxy.detector();
            mDetectorProxy.setCameraId(Camera.CameraInfo.CAMERA_FACING_FRONT);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mDetectorProxy != null) {
            mDetectorProxy.release();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.gc();
    }

    public void getFaceImg() {
        OkGo.<String>post("http://service.kantingyong.com/face/get")
                .tag(this)
                .headers("mbtToken", mbtToken)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //{"data":{"id":1,"imageurl":"http://oss-aliyun-liululu.oss-cn-shanghai.aliyuncs.com/upload/153537029700110310.jpg","status":1,"userid":36},"msg":"请求成功","resultCode":0}
                        FaceGetImgBean faceGetImgBean = JSON.parseObject(response.body(), FaceGetImgBean.class);
                        if (faceGetImgBean.getResultCode() == 0 && !faceGetImgBean.getData().getImageurl().isEmpty()) {
                            String imageurl = faceGetImgBean.getData().getImageurl();
                            url2Bitmap(imageurl);
                        } else {
                            isUploadFace = false;
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        isUploadFace = false;
                    }
                });

    }

    //上传人脸识别图片
    public void faceUpload(File file) {
        OkGo.<String>post("http://service.kantingyong.com/face/insert")
                .tag(this)
                .isMultipart(true)
                .headers("mbtToken", mbtToken)
                .params("file", file)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        //{"msg":"上传成功","resultCode":0}
                        if (progressDialog != null) {
                            progressDialog.cancel();
                        }
                        BaseBean baseBean = JSON.parseObject(response.body(), BaseBean.class);
                        Toast.makeText(mContext, baseBean.getMsg(), Toast.LENGTH_SHORT).show();
                        if (baseBean.getResultCode() == 0) {
                            finish();
                        }
                        mFace_detector_take_photo.setEnabled(true);
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        if (progressDialog != null) {
                            progressDialog.cancel();
                        }
                        resetinit();
                        mFace_detector_take_photo.setEnabled(true);
                    }
                });
    }

    //byte 转 File
    private void byte2file(byte[] bytes, String fileName) {
        /**
         * 创建File对象，其中包含文件所在的目录以及文件的命名
         */
        File file = new File(Environment.getExternalStorageDirectory(),
                fileName);
        // 创建FileOutputStream对象
        FileOutputStream outputStream = null;
        // 创建BufferedOutputStream对象
        BufferedOutputStream bufferedOutputStream = null;
        try {
            // 如果文件存在则删除
            if (file.exists()) {
                file.delete();
            }
            // 在文件系统中根据路径创建一个新的空文件
            file.createNewFile();
            // 获取FileOutputStream对象
            outputStream = new FileOutputStream(file);
            // 获取BufferedOutputStream对象
            bufferedOutputStream = new BufferedOutputStream(outputStream);
            // 往文件所在的缓冲输出流中写byte数据
            bufferedOutputStream.write(bytes);
            // 刷出缓冲输出流，该步很关键，要是不执行flush()方法，那么文件的内容是空的。
            bufferedOutputStream.flush();
        } catch (Exception e) {
            // 打印异常信息
            e.printStackTrace();
        } finally {
            // 关闭创建的流对象
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bufferedOutputStream != null) {
                try {
                    bufferedOutputStream.close();
                } catch (Exception e2) {
                    e2.printStackTrace();
                }
            }
            faceUpload(file);
        }
    }

    public String encodeImage(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 40, baos); //参数如果为100那么就不压缩
        byte[] bytes = baos.toByteArray();
        String encode = new BASE64Encoder().encode(bytes);
        return encode;
    }

    //url 转bitmap
    public void url2Bitmap(final String url) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                URL imageurl = null;

                try {
                    imageurl = new URL(url);
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                }
                try {
                    HttpURLConnection conn = (HttpURLConnection) imageurl.openConnection();
                    conn.setDoInput(true);
                    conn.connect();
                    InputStream is = conn.getInputStream();
                    netBitmap = BitmapFactory.decodeStream(is);
                    handler.sendEmptyMessage(1);
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    if (netBitmap != null) {
                        Base64NetStr = encodeImage(netBitmap);
                        isUploadFace = true;
                    }
                    break;
            }
        }
    };
}